package com.wiloon.tree;

import org.springframework.stereotype.Repository;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.List;

/**
 * Created by wiloon on 15-2-22.
 */
@Repository
public class NewsDaoImpl implements NewsDao {

    @PersistenceContext
    private EntityManager em;

    @Override
    public List<News> readAllNews() {
        CriteriaBuilder cb = em.getCriteriaBuilder();
        CriteriaQuery<News> cq = cb.createQuery(News.class);
        Root<News> news = cq.from(News.class);
        TypedQuery<News> tq = em.createQuery(cq);
        List<News> newsLst = tq.getResultList();
        return newsLst;
    }

    @Override
        public List<News> readNewsByUrl(String url) {
        CriteriaBuilder cb = em.getCriteriaBuilder();
        CriteriaQuery<News> cq = cb.createQuery(News.class);
        Root<News> news = cq.from(News.class);
        Predicate condition = cb.equal(news.get("link"),url);
        cq.where(condition);
        TypedQuery<News> tq = em.createQuery(cq);
        List<News> newsLst = tq.getResultList();
        return newsLst;
    }
}
